//utf-8

//选择合约
function toAddContract(){
	var dialogStruct={
			'display':contextRootPath+'/tCMmContract/prepareExecute/toSelectContract',
			'width':720,
			'height':600,
			'title':'选择合约',
			'isIframe':'false',
			'buttons':[]
		};
		
		var dialogAdd =jyDialog(dialogStruct).open();

	
}

//增加债权
function toAddDataCredit(){
	
	var value = $('#dtocooperorgCode').val();
	var redemptionDate = $('#redemptionDate').val();
	
	if(value==""|| null ==value){
		alert("请选择载入合约信息！");
		return;
	}
	
	var creditPackageName = $('#creditPackage option:selected').val();
	var redemptionDate = $('#redemptionDate').val();
	
	if(value!=null && value!=""){
		if(null==creditPackageName ||""==creditPackageName){
			alert("请选择包名！");
			return;
		}
		
		if(null==redemptionDate || ""==redemptionDate){
			alert("请选择赎回日期！");
			return;
		}
	}
	
	var dialogStruct={
			'display':contextRootPath+'/tCMmCreditDetail/prepareExecute/toAddRedempCredit',
			'width':800,
			'height':500,
			'title':'债权列表',
			'isIframe':'false',
			'buttons':[
			         {'text':'确定','action':doAddCredit,'isClose':true},
			  		 {'text':'关闭','isClose':true}
			]
		};
		
		var dialogAdd =jyDialog(dialogStruct).open();
}

//确认债权
function doAddCredit(obj){
	var table=iframeCredit.iframeObj["table"];
	var transferIds = table.getSelectedObjs("transferId");
	transferIds = "" + transferIds;
	var thisMakeCreditorValues = table.getSelectedObjs("thisMakeCreditorValue");
	thisMakeCreditorValues = "" + thisMakeCreditorValues;
	var ids = table.getSelectedObjs("id");
	ids = "" + ids;
	var dealCode = $('#dealCode').val();
	var redemptionDate = $('#redemptionDate').val();
	var id = $('#idValue').val();
	var creditPackageName = $('#creditPackage option:selected').val();
	var dataUrl =contextRootPath + "/creditRedem/updateCreditForRedemption";	
	var valueContractCode = $('#dtocontractCode').val();
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"transferIds":transferIds,
			"thisMakeCreditorValues":thisMakeCreditorValues,
			"ids":ids,
			"dealCode":dealCode,
			"id":id,
			"redeemDate":redemptionDate,
			"contractCode":valueContractCode,
			"packageNum":creditPackageName},
		error: function(result) {
			alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var obj = results.data;
			$("#idValue").val(obj.id);
			$("#dealCode").val(obj.dealCode);
			initFnCreditDetailView(transferIds);
			$("#creditDetailTable").show();
			CreditValueSum();
			$("#isDeleteAndIsExport").val("true");
			
		}
	});
}

//债权价值合计
function CreditValueSum(){
	var dealCode = $("#dealCode").val();
	var dataUrl =contextRootPath + "/loanRedem/getDealDetailByCreditSumTotal";	
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"dealCode":dealCode},
		error: function(result) {
			jyDialog({"type":"error"}).alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var obj = results.data;
			$("#detialNumber").val(obj.detialNumber);
			$("#sumMakeCreditorValue").val(obj.sumMakeCreditorValue);
		}
	});
}

//确认合约
function doAddFromContract(contractCode){	
	 window.location = contextRootPath+'/loanRedem/prepareExecute/toBackRedemptionAdd?contractCode='+contractCode;
	
}

//查询债权包	
var selectOptions=[];
function searchCreditPackage(selectID,updatePackageValue,type){
	var value = $('#dtocooperorgCode').val();
	if(value==""|| null ==value){
		return;
	}
	
	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var contractCode = $('#dtocontractCode').val();
	var dataUrl = contextRootPath + '/cooperorgDeal/getPackageList?cooperorgCode=' + valueCooperorgCode + "&contractCode=" + contractCode + "&pagType=" + cimsConstant.LOAN_RESOURCE;
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:'',
		error: function(result) {
			jyDialog({"type":"error"}).alert("请查看返回数据是否正确：" + result);
		},
		success: function(results) {
			var result=results.data;
			var j;
			var resultLength = result.length - 1;
			for (j = 0; j <= resultLength; j++) {
				$('#creditPackage').append("<option value='"+result[j].creditPackageName+"'>"+result[j].creditPackageName+"</option>");
				selectOptions.push(result[j].creditPackageName);
			}
			completePackage(selectOptions,selectID,updatePackageValue,type);
		}
	});

}

//保存交易流水
function saveCreditDeal(){
	
	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var valueContractCode = $('#dtocontractCode').val();
	var creditPackageName = $('#dealPackage').val();
	var dealCode = $('#dealCode').val();
	var id = $('#idValue').val();
	var sumCreditorValue = $('#sumCreditorValue').val();
	var detialNumber = $('#detialNumber').val();
	var dealType = $('#dealType').val();
	var dtoagreementCode = $('#dtoagreementCode').val();
	var redemptionDate = $('#redemptionDate').val();
	var valueSecondPagSuffix = $('#secondPagSuffix').val();
	var valueSecondCode = $('#secondCode').val();
	var sumCreditorValue = $('#sumCreditorValue').val();
	
 
	if(null==valueCooperorgCode||""==valueCooperorgCode){
		jyDialog({"type":"error"}).alert("请选择合约!");
		return;
	}
	if("submitting"== dealCode){
		jyDialog({"type":"error"}).alert("信息正在保存，请稍后！");
		return;
	}
	
	if(null!=dealCode && ""!=dealCode){
		jyDialog({"type":"error"}).alert("信息已保存，流水号为："+dealCode);
		return;
	}
	if(null==creditPackageName||""==creditPackageName){
		jyDialog({"type":"error"}).alert("请选择债权包编号!");
		return;
	}
	
	if(null==redemptionDate||""==redemptionDate){
		jyDialog({"type":"error"}).alert("请选择回购日期!");
		return;
	}

	jyDialog({"type":"question"}).confirm("您确认要保存吗？",function(){
		saveRedemptionDeal();
	},"保存确认提示");
}
function saveRedemptionDeal(){
	$('#dealCode').val("submitting");
	
	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var valueContractCode = $('#dtocontractCode').val();
	var creditPackageName = $('#dealPackage').val();
	var dealCode = $('#dealCode').val();
	var id = $('#idValue').val();
	var sumCreditorValue = $('#sumCreditorValue').val();
	var detialNumber = $('#detialNumber').val();
	var dealType = $('#dealType').val();
	var dtoagreementCode = $('#dtoagreementCode').val();
	var redemptionDate = $('#redemptionDate').val();
	var valueSecondPagSuffix = $('#secondPagSuffix').val();
	var valueSecondCode = $('#secondCode').val();
	var sumCreditorValue = $('#sumCreditorValue').val();
	
	var dataUrl = contextRootPath + '/loanRedem/saveRedemptionDeal?creditPackage=' 
					+ creditPackageName + "&valueSecondPagSuffix=" + valueSecondPagSuffix 
					+ "&valueSecondCode=" + valueSecondCode+ "&redemptionDate=" + redemptionDate
					+ "&deleteContractNos=" + deleteContractNos;
	var params = {
		"cooperorgCode" : valueCooperorgCode,
		"contractCode" : valueContractCode,
		"creditPackageName" : creditPackageName,
		"id" : id,
		"sumCreditorValue" : sumCreditorValue,
		"detialNumber" : detialNumber,
		"dealType" : dealType,
		"agreementCode" : dtoagreementCode,
		"redemptionDate" : redemptionDate
	};
	jyAjax(
			dataUrl,
			params, 
			function(results){
				var v_status = results.status;
	        	if(v_status.indexOf('ok') >-1){
	        		$("#isDeleteAndIsExport").val("true");
					var obj = results.data;
					$("#dealCode").val(obj.dealCode);
					CreditValueSum();
					$("#exportButton").show();
			   		$("#importButton").show();
			   		$("#finishButton").show();
			   		$("#saveCreditDealBtn").hide();
			   		$("#dealPackage").prop("disabled",true);
			   		$("#redemptionDate").prop("disabled",true);
			   		initFnCreditDetailView();
			   		var winObj = parent.tabs.getTabWinByTitle("贷款回购");
			   		if(winObj) {
						winObj.location.reload();
			   		} 
			   		jyDialog({"type":"info"}).alert(results.msg);
			   		$("#isNew").val("");
	        	}
	         },
	        function(results){
	        	$('#dealCode').val("");
	        	jyDialog({"type":"error"}).alert(results.msg);
	        	},
	        "POST");
}

//试算
function settleCreditDeal(){
	var dealCode = $('#dealCode').val();
	
	if(null==dealCode||""==dealCode){
		alert("请先导入债权确认信息！");
		return;
	}
	
	if(confirm("请确认导入的债权信息!")){
		var dataUrl =contextRootPath + "/settle/testSettleCooperorgDeal";
		$.ajax({
			url: dataUrl,
			type: 'post',
			dataType: 'json',
			data:{"dealCode":dealCode},
			error: function(result) {
				alert("请查看返回数据是否正确：" + result);
			},
			success: function(results) {
				
			}
		});
	}
}

//债权包输入
function creditPackageOperation(obj){
	
 
	
}

//删除债权
function deleteCredit(){
	
	var isDeleteAndIsExport = $("#isDeleteAndIsExport").val();
	if(false==isDeleteAndIsExport||"false"==isDeleteAndIsExport){
		alert("没有债权可删除，请新增！");
		return;
	}
	
	var table=iframeCreditView.iframeObj["table"];
	var transferIds = table.getSelectedObjs("transferId");
	transferIds = transferIds + "";
	var v_ids = iframeCreditView.iframeObj["table"].getSelectedIds().join(",");
	//如果没有选中 数据则
	if(v_ids == ""){
		alert("请选择待删除的数据！");
		return;
	}
	if(confirm("您确认要删除选择的数据吗？")){
        $.ajax({
            type:"POST",
            dataType : "json",
            url:contextRootPath+"/creditRedem/deleteDetailByCredit",
            data:{"transferIds":transferIds},
            success:function(msg){
            	alert(msg.msg);
            	var v_status = msg.status;
            	//删除成功后
            	if(v_status.indexOf('ok') >-1){
            		iframeCreditView.iframeObj["table"].removeSelectedRow();
            		CreditValueSum();
            	}
            	
            	
            }
        });
    }
}

//完成按钮操作-验证合作机构交易状态，交易状态非03-回购成功的均可以调用，否则交易将发生错误
function finishCreditDeal(){
	var dealCode = $('#dealCode').val();
	if(null==dealCode ||""==dealCode){
		alert("你没有选中交易流水号！");
		return;
	}
	saveDeal(dealCode);
}

//完成按钮操作,分步进行操作
/**
 * 1. 首先弹出提示信息，是否“确认发往核心进行贷款回购处理？”，若“确认”，则需要进行合法性校验；若“关闭”，则关闭本窗口，不做任何操作
 * 2. 其次进行合法性校验1，验证其确认日期及回购日期，保证确认日期必须大于等于回购日期，若小于弹出提示信息，反之不提示(即做业务人员可推后做业务，但不能提前做业务)；
 * 3. 再其次进行合法性校验2，验证跨账单日，若含跨账单日信息，则弹出失败信息，若不含跨账单日信息，则不提示；
 * */
function saveDeal(dealCode){
	if ($("#sendFlag").val() == "SENDING") {
		jyDialog({"title":"test","type":"warn"}).alert("正在调用核心接口，请等待!");
		return;
	}else if($("#sendFlag").val() == "OK"){
		jyDialog({"title":"test","type":"warn"}).alert("调用核心接口已成功，无需再次调用!");
		return;
	}else if($("#sendFlag").val() == "FAILED" || $("#sendFlag").val() == ""){
		jyDialog({"type":"question"}).confirm("确认发往核心进行贷款回购处理？",function(){
			validateLoanTransferBusinessValid(dealCode);
		},"一次提示");
	}
}

//验证贷款转出业务合法性
function validateLoanTransferBusinessValid(dealCode){
	var dataUrl =contextRootPath + "/loanRedem/getLoanTransferBusinessValid";
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:{"dealCode":dealCode},
		success: function(results) {
			if(results.status == "ok"){
				//业务合法性验证通过，继续验证跨账单日函数
//				validateLoanTransferCrossBillDate(dealCode);
				doLoanTransferRedeem(dealCode)
			}else{
				//业务合法性验证不通过，弹出提示信息
				jyDialog({"title":"test","type":"warn"}).alert(results.msg);
			}
		}
	});
}

/**验证跨账单日函数
 * 业务逻辑如下：
 * 1. 若含跨账单日信息，则弹出提示信息，是否继续调用核心接口处理？
 * 2. 反之，则直接调用核心接口进行处理。
**/
function validateLoanTransferCrossBillDate(dealCode){
	var dataUrl =contextRootPath + "/loanRedem/getLoanTransferCrossBillDate";
	$.ajax({
		url: dataUrl,
		type: 'get',
		dataType: 'json',
		data:{"dealCode":dealCode},
		success: function(results) {
			if(results.status == "ok"){
				doLoanTransferRedeem(dealCode);
			}else{
				jyDialog({"type":"question"}).confirm(results.msg+"<br\><br\>确认仍继续发往核心进行贷款回购处理？",function(){
					doLoanTransferRedeem(dealCode);
				},"二次提示");
			}
		}
	});
}

//调用核心贷款回购事务处理
function doLoanTransferRedeem(dealCode){
	//处理中
	$("#sendFlag").val("SENDING");
	var dataUrl =contextRootPath + "/loanRedem/saveLoanTransferRedeem";
	var params = {"dealCode":dealCode};
	
	jyAjax(
			dataUrl, 
			params, 
			function(results) {//成功
				$("#importButton").hide();
				$("#finishButton").hide();
			    $('#cooperativeAgencyDealStatus').val('03');
			    $("#sendFlag").val("OK");
			    $("#queryMatchCredit").show();//贷款回购成功后，显示【查看匹配债权信息】按钮
				var winObj = parent.tabs.getTabWinByTitle("贷款回购");
				if(winObj) {
					winObj.location.reload();
				}
				initFnCreditDetailView();
				if(results.msg != null){
					var msg = results.msg;
					var status = results.status;
					if (msg.indexOf("@@") > -1) {
						var strs=msg.split("@@"); //字符分割 
						var showMsg1 = strs[0] != "" ? "● "+ strs[0] : "";
						showMsg1 += strs[1] != "" ? "<br\><br\>● "+ strs[1] : "";
						jyDialog({"type":"error"}).alert(showMsg1);
					} else {
						jyDialog({"type":"error"}).alert(msg);
					}
				}
			}, 
			function(results) {//失败
				$("#sendFlag").val("FAILED");
				if(results.msg != null){
					var msg = results.msg;
					if (msg.indexOf("@@") > -1) {
						var strs=msg.split("@@"); //字符分割 
						var showMsg1 = strs[0] != "" ? "● "+ strs[0] : "";
						showMsg1 += strs[1] != "" ? "<br\><br\>● "+ strs[1] : "";
						jyDialog({"type":"error"}).alert(showMsg1);
					} else {
						jyDialog({"type":"error"}).alert(msg);
					}
				}
			});
}

//当日期发生变化时触发
function refreshCreditDetail(obj){
	var value = $('#dtocooperorgCode').val(); // 合约信息
	var redemptionDate = $('#redemptionDate').val();// 赎回日期
	var creditPackageName = $('#creditPackage option:selected').val();// 债权包包号
	
	// 基本信息校验
	if(value==""|| null ==value){
		jyDialog({"type":"error"}).alert("请选择载入合约信息！");
		return;
	}	 
	if(value!=null && value!=""){
		if(null==creditPackageName ||""==creditPackageName){
			jyDialog({"type":"error"}).alert("请选择债权包！");
			return;
		}
		
		if(null==redemptionDate || ""==redemptionDate){
			jyDialog({"type":"error"}).alert("请选择赎回日期！");
			return;
		}
	}
	initFnCreditDetailView();
	$("#creditDetailTable").show();
}


function transfereeImport(){
	var creditPackageWrite = $('#dealPackage').val(); //包
	var dtocontractCode = $('#dtocontractCode').val();  //合约编号
	var dealType = $("#dealType").val();//业务类型
	var className = "com.jy.modules.cims.data.dto.CreditDetailDto"; //实体
	/**
	 * 调用公用的导入方法
	 */
	publicImportMothed(dtocontractCode,dealType,cimsConstant.SESSION_IMPORT_DATA_PATH,className,creditPackageWrite,"callback();");
}


/**
 *回调方法
 */
function callback(){
	var importDataId = $("#importDataId").val();//excel解析数据的数据KEY
	var dealCode = $('#dealCode').val(); //交易流水号
	var valueCooperorgCode = $('#dtocooperorgCode').val();//转让机构编号
	var creditPackage = $('#creditPackageWrite').val(); //包
	var dtocontractCode = $('#dtocontractCode').val();  //合约编号
	var dtoagreementCode = $('#dtoagreementCode').val(); //协议编号
	var flag = "";
	$.ajax({
        type:"post",
        dataType: 'json',
        async:false,
        url:contextRootPath+"/loanRedem/doTransfereeDeal",
        data:{
       	 "packageNum":creditPackage,
       	 "contractCode":dtocontractCode,
       	 "agreementCode":dtoagreementCode,
       	 "cooperorgCode":valueCooperorgCode,
       	 "dealCode":dealCode,
       	 "dataType":"01",
       	 "dataId":importDataId
        },
        success:function(msg){
        	if(msg.status=="ok"){
        		
        	
	        	var dto = msg.data;
	        	if(dto!=null){
	            	$('#dealCode').val(dto.dealCode);
	            	//加载债权信息
	            	initFnCreditDetailView();
	            	CreditValueSum();
	    			$("#creditDetailTable").show();
	        	}
	        	flag = "处理成功";
        	}else {
        		flag = "处理失败:"+msg.msg;
        	}
        	
        }
    });
	return flag;
}
//确认导出
function sureExportForLoan(){
	var isDeleteAndIsExport = $("#isDeleteAndIsExport").val();
	if(false==isDeleteAndIsExport || "false"==isDeleteAndIsExport){
		alert("请先保存交易！");
		return;
	}
	
	var obj  = $('#contractCode').length;
	var valueContractCode;
	if(obj>0){
		valueContractCode = $('#contractCode').val();
	}else {
		valueContractCode = $('#dtocontractCode').val();
	}
	
	var valueCooperorgCode = $('#dtocooperorgCode').val();
	var dealCode = $('#dealCode').val();
	if(""==valueContractCode || null==valueContractCode){
		alert("请选择合约！");
		return;
	}
	var creditPackage = $('#dealPackage').val();
	
	var exportTypeValue ="" + $("#exportType").val();
	var fileName = $('#fileName').val();
	var dealType = $('#dealType').val();
	var exportType="";
	if("credit"==exportTypeValue){
		exportType="credit";
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/cimsCascade/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}else if("loan"==exportTypeValue){
		exportType="loan";
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/cimsCascade/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}else if("redemption"==exportTypeValue){
		exportType="redemption";
		var templateType="00";
		if(""!=dealType && null!=dealType){
			templateType = dealType;
		}
		var isPlan = $("#isPlan").val();
		var contractCode = valueContractCode;
		var url = contextRootPath + '/loanRedem/exportDataName?contractCode=' + valueContractCode + "&dealCode=" + dealCode + "&exportType=" + exportType +"&fileName=" + fileName + "&creditorAffirmRule=" + dealType + "&isPlan=" + isPlan+"&creditPackage="+creditPackage;
		isNotTemplate(contractCode,templateType,url);
	}	
}


//查看贷款回购匹配的债权信息
function queryMatchCredit() {
	var dialogStruct={
			'display':contextRootPath+'/loanRedem/prepareExecute/intoMatchCredit',
			'width':1000,
			'height':600,
			'title':'查看匹配债权信息',
			'isIframe':'false',
			'buttons':[]
		};
	var dialogMatch =jyDialog(dialogStruct).open();

}

function finishDeal(){
	
	var dealCode = $('#dealCode').val(); //交易流水号
	var valueCooperorgCode = $('#dtocooperorgCode').val();//转让机构编号
	
	if(null==valueCooperorgCode ||""==valueCooperorgCode){
		alert("请选择合作机构！");
		return;
	}
	if(dealCode==""){
		alert("请先点击保存！");
	}
	var dataUrl =contextRootPath + "/loanRedem/finishDeal";
	$.ajax({
		url: dataUrl,
		type: 'post',
		dataType: 'json',
		data:{"cooperorgCode":valueCooperorgCode,"dealCode":dealCode},
		success: function(results) {
			if(results.status=="failed"){
				alert("发送完成失败！"+results.msg);
			}else{
				alert("发送完成成功！");
			}
		}
	});
	
}

